﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace Wolfy.SuperWatherService
{
    class Program
    {
        static void Main(string[] args)
        {
            //如果传递了参数 s 就从控制台启动服务
            if (args.Length > 0 && args[0] == "s")
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] { new WatherService() };
                ServiceBase.Run(ServicesToRun);
            }
            else
            {
                //注册或者卸载服务
                Console.WriteLine("This is Windows service setup application ...");
                Console.WriteLine("Please choice，[1]SetUp Service [2]Delete Service [3]Quit");
                var rs = int.Parse(Console.ReadLine());
                string configWathServiceName = ConfigurationManager.AppSettings["toWatchServiceName"];
                if (rs == 1)
                {
                    if (string.IsNullOrEmpty(configWathServiceName))
                    {
                        while (true)
                        {
                            Console.WriteLine("Please input the service name,You hope to watch it.");
                            string strName = Console.ReadLine();
                            if (!string.IsNullOrEmpty(strName))
                            {
                                if (CheckServiceIsExists(strName))
                                {
                                    Configuration cfa =
   ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                                    cfa.AppSettings.Settings["toWatchServiceName"].Value = strName;
                                    cfa.Save();
                                    break;
                                }
                                else
                                {
                                    Console.WriteLine("{0} servie not exist!", strName);
                                }
                            }
                        }
                    }
                    string strInterval = ConfigurationManager.AppSettings["timerInterval"];
                    if (string.IsNullOrEmpty(strInterval))
                    {
                        while (true)
                        {
                            Console.WriteLine("Please input the interval(s) to check service is running.");
                            string inputInterval = Console.ReadLine();
                            if (!string.IsNullOrEmpty(inputInterval))
                            {
                                Configuration cfa =
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                                cfa.AppSettings.Settings["timerInterval"].Value = inputInterval;
                                cfa.Save();
                                break;
                            }
                        }
                    }
                }
                string strServiceName = configWathServiceName + " Watcher Service";
                switch (rs)
                {
                    case 1:
                        //取当前可执行文件路径，加上"s"参数，证明是从windows服务启动该程序
                        var path = Process.GetCurrentProcess().MainModule.FileName + " s";
                        Process.Start("sc", "create " + strServiceName + " binpath= \"" + path + "\" displayName= " + strServiceName + " start= auto");
                        Console.WriteLine("SetUp Success ");
                        Console.Read();
                        break;
                    case 2:
                        Process.Start("sc", "delete " + strServiceName + "");
                        Console.WriteLine("Delete Success");
                        Console.Read();
                        break;
                    case 3: break;
                }

            }
        }
        /// <summary>
        /// 检验服务是否存在
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        static bool CheckServiceIsExists(string serviceName)
        {
            bool result = false;
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController service in services)
            {
                if (service.ServiceName.Trim() == serviceName.Trim())
                {
                    result = true;
                }
            }
            return result;
        }

    }
}
